package com.affectu.user.action;

import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.hibernate.Query;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.faces.FacesMessages;
import org.jboss.seam.international.StatusMessage.Severity;
import org.jboss.seam.security.Identity;

import com.affectu.dao.DAOBase;
import com.affectu.user.User;

/**
 * Oct 28, 2008
 * 
 * @author daniel nathan
 */
@Name("registerAction")
public class Register extends DAOBase {

	@SuppressWarnings("deprecation")
	public String addUser(User user) {
		String url = "";
		try {
			if (this.isUserExsit(user)) {
				FacesMessages.instance().add("此用户已经存在");
			} else {
				em.persist(user);
				Identity.instance().setUsername(user.getEmail());
				Identity.instance().setPassword(user.getPassword());
				Identity.instance().login();
				this.setCurrentUserToSession(user);
				url = "/passport/index.xhtml";
			}

		} catch (Exception ex) {
			this.logAffectuException(ex, "注册出错");
		}
		return url;
	}

	@SuppressWarnings("unchecked")
	public boolean isUserExsit(User user) {
		boolean flag = false;
		try {
			List users = em.createQuery(
					"select u from User u where u.nickName=:nickName")
					.setParameter("nickName", user.getNickName()).list();
			if (users.size() > 0) {
				flag = true;
			}
		} catch (Exception ex) {
			this.logException(ex);
		}
		return flag;
	}

	public String verifyUser(User user) {
		if (this.checkEmailFormat(user.getEmail())) {
			FacesMessages.instance().add("Email格式不正确");
			return "";
		}
		if (this.checkEmail(user.getEmail())) {
			FacesMessages.instance().addToControl("email", "该email已经被注册");
		}
		if (!user.getPassword().equals(user.getPasswordConfirm())) {
			// Severity severity=new Severity();
			FacesMessages.instance().addToControl("verify", Severity.ERROR,
					"密码输入不一致");// .add(Severity.ERROR,"密码输入不一致");
		}
		return "";
	}

	private boolean checkEmail(String email) {
		boolean flag = false;
		try {
			Query query = em.createQuery("from User u where u.email=:email")
					.setString("email", email);
			if (query.list().size() > 0) {
				flag = true;
			}
		} catch (Exception ex) {
			this.logException(ex);
		}
		return flag;

	}

	private boolean checkEmailFormat(String email) {
		boolean flag = false;
		try {
			String REGEX = "^([0-9a-zA-Z]+[_.0-9a-zA-Z-]+)@([a-zA-Z0-9-]+[.])+([a-zA-Z]{2,3})$";
			Pattern p = Pattern.compile(REGEX, Pattern.DOTALL);
			Matcher matcher = p.matcher(email); // get a matcher object
			if (matcher.matches()) {
				flag = true;
			}
		} catch (Exception ex) {
			this.logException(ex);
		}
		return flag;
	}
}
